import 'package:trade/data/apis/k_line_api.dart';
import 'package:trade/data/bean/market_data_bean.dart';
import 'package:trade/pages/trading_page/bean/market_price.dart';
import 'package:trade/pages/trading_page/bean/period.dart';
import 'package:trade/widgets/loading/loading_util.dart';
import '../../../common/base/view_model.dart';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/services.dart';
import 'package:flutter_k_chart/flutter_k_chart.dart';

class TradingModel extends ViewModel {
  List<String> tradePairs = [
    "BTC/USDT",
    "ETH/USDT",
    "EOS/USDT",
    "XRP/USDT",
    "FIL/USDT",
    "DOT/USDT",
  ];

  String token = "";
  List<TradePairViewBean> tradePairBeans = [];
  List<KLineEntity> data = [];
  String _currentPair = "BTC/USDT";

  String get currentPair => _currentPair;

  set currentPair(String value) {
    _currentPair = value;
    hasLast = false;
    getKlineData();
    notifyListeners();
  }

  void _getTradePairData() {
    tradePairBeans.clear();
    tradePairBeans = tradePairs
        .map((e) => TradePairViewBean(
            name: e.toUpperCase(), price: "35000", isRise: true))
        .toList();
  }

  set notifyTradePairs(List<String> tradePairs) {
    this.tradePairs = tradePairs;
    _getTradePairData();
    notifyListeners();
  }

  set notifyChartData(List<dynamic> listMap) {
    data = listMap
        .map((item) => KLineEntity.fromJson(item))
        .toList()
        .reversed
        .toList()
        .cast<KLineEntity>();
    this.data = data;
    DataUtil.calculate(data);
    _getTradePairData();
    notifyListeners();
  }

  /// 周期数组
  List<Period> periodList = [
    Period.minutes1(),
    Period.minutes5(),
    Period.minutes15(),
    Period.minutes30(),
    Period.hours1(),
    Period.hours4(),
    Period.day1(),
    Period.week1(),
    Period.month1(),
  ];

  /// 当前选择的K线周期,默认为1周
  Period _currentPeriod = Period.minutes1();

  Period get currentPeriod => _currentPeriod;

  set currentPeriod(Period value) {
    _currentPeriod = value;
    hasLast = false;
    getKlineData();
  }

  /// 正在请求先等上一个请求完成再继续请求
  String _loadingPeriodId = "";
  bool isKlineDataLoading = false;

  Future<void> getKlineData(
      {int size = 500, bool updateLastLine = false}) async {
    if (_loadingPeriodId == _currentPeriod.id && true == isKlineDataLoading)
      return;
    isKlineDataLoading = true;
    _loadingPeriodId = _currentPeriod.id;
    if (false == updateLastLine) {
      showLoading();
    }
    String symbol;
    if (_currentPair == "BTC/USDT") {
      symbol = "btcusdt";
    } else if (_currentPair == "ETH/USDT") {
      symbol = "ethusdt";
    } else if (_currentPair == "EOS/USDT") {
      symbol = "eosusdt";
    } else if (_currentPair == "XRP/USDT") {
      symbol = "xrpusdt";
    } else if (_currentPair == "FIL/USDT") {
      symbol = "filusdt";
    } else if (_currentPair == "DOT/USDT") {
      symbol = "dotusdt";
    } else {
      symbol = "";
    }

    await getList(symbol, _currentPeriod.id, size.toString(), token,
        updateLastLine: updateLastLine);
    isKlineDataLoading = false;
    dismissLoading();
    return Future.value();
  }

  MarketDataBean tickerBean = MarketDataBean();
  bool hasLast = false;
  getList(String symbol, String period, String size, String token, {bool updateLastLine = false}) async {
    var result =
    await KLineListApi(symbol, period, size).request(token: token);
    tickerBean = result.tickerBean;
    if (updateLastLine && this.data.length > 0) {
      if (result.klineData != null) {
        List<KLineEntity> news = result.klineData!
            .map((item) => KLineEntity.fromJson(item))
            .toList()
            .reversed
            .toList()
            .cast<KLineEntity>();

        if (news.isNotEmpty) {
          // DataUtil.calculate(news);
          var newest = news.last;
          var last = this.data.last;
          if (last.id == newest.id) {
            last.vol = newest.vol;
            last.close = newest.close;
            last.high = newest.high;
            last.low = newest.low;
            last.amount = newest.amount;
            last.count = newest.count;
            DataUtil.updateLastData(this.data);
          } else {
            DataUtil.addLastData(this.data, newest);
          }

          notifyListeners();
        }
      }
    } else {
      if (result.klineData != null) {
        this.notifyChartData = result.klineData!;
      }
    }
  }
}

class TradePairViewBean {
  String name;
  String price;
  bool isRise;

  TradePairViewBean({
    this.name = '',
    this.price = '',
    this.isRise = true,
  });
}
